//
//  SignUpViewController.m
//  shusheng
//
//  Created by rimi on 16/7/11.
//  Copyright © 2016年 yuying. All rights reserved.
//

#import "SignUpViewController.h"
#import "CDCacheManager.h"
#import "CDChatManager.h"
#import "CDIMService.h"
#import "CDUserManager.h"
@interface SignUpViewController ()
//@property(strong,nonatomic)UIButton *phoneSignUpBtn;
@property (strong,nonatomic) UILabel     *footLabel;
@property (strong,nonatomic) UIButton    *footButton;
@property (strong,nonatomic) UILabel     *titleLabel;
@property (strong,nonatomic) UIImageView *backgroundImg;
@property (strong,nonatomic) UIButton    *signUpBtn;
@property (strong,nonatomic) UIButton    *backBtn;
@property (strong,nonatomic) UITextField *userNameTextField;
@property (strong,nonatomic) UITextField *emailTextField;
@property (strong,nonatomic) UITextField *passwordTextField;
@property (strong,nonatomic) UITextField *affirmPasswordTextField;
@property (strong,nonatomic) UILabel     *loginLabel;
@property (strong,nonatomic) UIButton    *loginBtn;
- (void)initializeInterface;  //初始化用户界面
@end

@implementation SignUpViewController
- (void)dealloc {
    // 移除通知
    // ARC模式下无需调用[super dealloc];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma make -- LifeCycle --
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
    [self initializeInterface];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)initializeInterface{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.backgroundImg];
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.userNameTextField];
    [self.view addSubview:self.passwordTextField];
    [self.view addSubview:self.affirmPasswordTextField];
    [self.view addSubview:self.emailTextField];
    [self.view addSubview:self.signUpBtn];
    [self.view addSubview:self.backBtn];
    [self.view addSubview:self.footLabel];
    [self.view addSubview:self.footButton];
    
    
}
#pragma make -- Action --

//注册
-(void)signUPBtnAction{
    [self affirmPassword];
    AVUser *user = [AVUser user];// 新建 AVUser 对象实例
    user.username = self.userNameTextField.text;// 设置用户名
    user.password = self.passwordTextField.text;// 设置密码
    user.email = self.emailTextField.text;      //设置邮箱
    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            // 注册成功
            NSLog(@"注册成功");
            [MBProgressHUD showSuccess:@"注册成功"];
            [[CDUserManager manager]loginWithInput:self.userNameTextField.text password:self.passwordTextField.text block:^(AVUser *user, NSError *error) {
                [MBProgressHUD hideHUD];
                if (error == nil) {
                    [[NSUserDefaults standardUserDefaults] setObject:self.userNameTextField.text forKey:KEY_USERNAME];
                    [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:@"psw"];
                    MainViewController *mainVC = [[MainViewController alloc]init];
                    [self presentViewController:mainVC animated:YES completion:^{
                        [self.view removeFromSuperview];
                        [self removeFromParentViewController];
                    }];
                    // 登录进入主页
                    [[CDCacheManager manager] registerUsers:@[[AVUser currentUser]]];
                    [CDChatManager manager].userDelegate = [CDIMService service];
                    
#ifdef DEBUG
#warning 使用开发证书来推送，方便调试，具体可看这个变量的定义处
                    [CDChatManager manager].useDevPushCerticate = YES;
#endif
                    
                    //提示正在登陆
                    //                            [MBProgressHUD showMessage:@"登录中"];
                    [[CDChatManager manager] openWithClientId:[AVUser currentUser].objectId callback: ^(BOOL succeeded, NSError *error) {
                        //        [MBProgressHUD hideHUD];
                        if (succeeded) {
                            NSLog(@"登录成功");
                        } else {
                            
                            
                        }
                        
                    }];
                }else{
                    [MBProgressHUD showError:error.detialMessage];
                }
            }];
            
            
            
        } else {
            // 失败的原因可能有多种，常见的是用户名已经存在。
            NSLog(@"%@",error);
            [MBProgressHUD showError:[error detialMessage]];
            
        }
    }];
    
}

//密码确认
-(void)affirmPassword{
    if (![self.passwordTextField.text isEqualToString:self.affirmPasswordTextField.text]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"2次密码不同" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        self.passwordTextField.text = @"";
        self.affirmPasswordTextField.text = @"";
    }
}

//返回
-(void)backBtnAction{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark -- 键盘处理
// 键盘处理
- (void)keyBoardWillAppear:(NSNotification *)notification {
    self.view.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds) - 200);
}

// 键盘处理
- (void)keyBoardWillHidden:(NSNotification *)notification {
    self.view.center = CGPointMake(CGRectGetMidX(self.view.bounds), [UIScreen mainScreen].bounds.size.height / 2);
}

#pragma mark *** Touches methods ***
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // 收起键盘
    [self.view endEditing:YES];
}
#pragma make -- Getter --
-(UIImageView *)backgroundImg{
    if (!_backgroundImg) {
        _backgroundImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"loginback.jpeg"]];
        _backgroundImg.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
        //  创建需要的毛玻璃特效类型
        UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        //  毛玻璃view 视图
        UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
        //添加到要有毛玻璃特效的控件中
        effectView.frame = _backgroundImg.bounds;
        [_backgroundImg addSubview:effectView];
        //设置模糊透明度
        effectView.alpha = 0.7;
    }
    return _backgroundImg;
}

-(UIButton *)signUpBtn{
    if (!_signUpBtn) {
        _signUpBtn = [[UIButton alloc]init];
        _signUpBtn.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds)-100, 50);
        _signUpBtn.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.emailTextField.frame)+35);
        [_signUpBtn setBackgroundColor:RGB_COLOR(255, 255, 255, 0.4)];
        _signUpBtn.layer.masksToBounds = YES;
        _signUpBtn.layer.cornerRadius = 10;
        [_signUpBtn setTitle:@"注册" forState:UIControlStateNormal];
        [_signUpBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_signUpBtn addTarget:self action:@selector(signUPBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _signUpBtn;
}

-(UILabel *)footLabel{
    if (!_footLabel) {
        _footLabel = [[UILabel alloc]init];
        _footLabel.bounds = CGRectMake(0, 0, 150, 30);
        _footLabel.font = [UIFont systemFontOfSize:15];
        _footLabel.center = CGPointMake(CGRectGetMidX(self.view.frame)-50, CGRectGetMaxY(self.signUpBtn.frame)+80);
        _footLabel.text = @"已经有一个账号了吗？";
        [_footLabel setTextColor:RGB_COLOR(240, 240, 240, 1)];
    }
    return _footLabel;
}
-(UIButton *)footButton{
    if (!_footButton) {
        _footButton = [[UIButton alloc]init];
        _footButton.bounds = CGRectMake(0, 0, 70, 50);
        _footButton.center = CGPointMake(CGRectGetMaxX(self.footLabel.frame)+30, CGRectGetMidY(self.footLabel.frame));
        [_footButton setTitle:@"登录" forState:UIControlStateNormal];
        [_footButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_footButton addTarget:self action:@selector(backBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _footButton;
}
-(UIButton *)backBtn{
    if (!_backBtn) {
        _backBtn = [[UIButton alloc]init];
        _backBtn.bounds = CGRectMake(0, 0, 70, 20);
        _backBtn.center = CGPointMake(CGRectGetMinX(self.view.frame)+30, CGRectGetMinY(self.view.frame)+42);
        [_backBtn setBackgroundColor:[UIColor clearColor]];
        [_backBtn setTitle:@"<返回" forState:UIControlStateNormal];
        [_backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

-(UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds)/4, 100);
        _titleLabel.center = CGPointMake(CGRectGetWidth(self.view.bounds)/8+20, CGRectGetMaxY(self.backBtn.frame)+70);
        _titleLabel.text =@"注册";
        _titleLabel.font = [UIFont systemFontOfSize:50];
        [_titleLabel setTextColor:[UIColor whiteColor]];
    }
    return _titleLabel;
}

-(UITextField *)passwordTextField{
    if (!_passwordTextField) {
        _passwordTextField = [[UITextField alloc]init];
        _passwordTextField.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds)-100, 50);
        _passwordTextField.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.userNameTextField.frame)+35);
        [_passwordTextField setBackgroundColor:RGB_COLOR(255, 255, 255, 0.4)];
        _passwordTextField.placeholder = @"请输入密码";
        _passwordTextField.secureTextEntry = YES;
        _passwordTextField.layer.masksToBounds = YES;
        _passwordTextField.layer.cornerRadius = 10;
        _passwordTextField.keyboardType = UIKeyboardTypeDefault;
        _passwordTextField.borderStyle = UITextBorderStyleBezel;
        //asdsad
    }
    return _passwordTextField;
}

-(UITextField *)affirmPasswordTextField{
    if (!_affirmPasswordTextField) {
        _affirmPasswordTextField = [[UITextField alloc]init];
        _affirmPasswordTextField.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds)-100, 50);
        _affirmPasswordTextField.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.passwordTextField.frame)+35);
        [_affirmPasswordTextField setBackgroundColor:RGB_COLOR(255, 255, 255, 0.4)];
        _affirmPasswordTextField.placeholder = @"请再次输入密码";
        _affirmPasswordTextField.secureTextEntry = YES;
        _affirmPasswordTextField.layer.masksToBounds = YES;
        _affirmPasswordTextField.layer.cornerRadius = 10;
        _affirmPasswordTextField.keyboardType = UIKeyboardTypeDefault;
        _affirmPasswordTextField.borderStyle = UITextBorderStyleBezel;
    }
    return _affirmPasswordTextField;
}
-(UITextField *)emailTextField{
    if (!_emailTextField) {
        _emailTextField = [[UITextField alloc]init];
        _emailTextField.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds)-100, 50);
        _emailTextField.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.affirmPasswordTextField.frame)+35);
        [_emailTextField setBackgroundColor:RGB_COLOR(255, 255, 255, 0.4)];
        _emailTextField.placeholder = @"请输入邮箱";
        _emailTextField.secureTextEntry = NO;
        _emailTextField.layer.masksToBounds = YES;
        _emailTextField.layer.cornerRadius = 10;
        _emailTextField.keyboardType = UIKeyboardTypeDefault;
        _emailTextField.borderStyle = UITextBorderStyleBezel;
    }
    return _emailTextField;
}

-(UITextField *)userNameTextField{
    if (!_userNameTextField) {
        _userNameTextField = [[UITextField alloc]init];
        _userNameTextField.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds)-100, 50);
        _userNameTextField.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMidY(self.view.frame)-100);
        [_userNameTextField setBackgroundColor:RGB_COLOR(255, 255, 255, 0.4)];
        _userNameTextField.placeholder = @"请输入用户名";
        _userNameTextField.secureTextEntry = NO;
        _userNameTextField.layer.masksToBounds = YES;
        _userNameTextField.layer.cornerRadius = 10;
        _userNameTextField.keyboardType = UIKeyboardTypeDefault;
        _userNameTextField.borderStyle = UITextBorderStyleBezel;
    }
    return _userNameTextField;
}
@end
